//
//  OSSImageUploader.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/4.
//


import AliyunOSSiOS
import SwiftUI

class OSSImageUploader: ObservableObject {
    private var client: OSSClient?
    @Published var uploadProgress: Double = 0
    @Published var uploadResult: String = ""
    static let shared = OSSImageUploader()
    init() {
        setupOSSClient()
    }
    
    private func setupOSSClient() {
        let credential = OSSStsTokenCredentialProvider(
            accessKeyId: "LTAI5tF342hdCmFEAjrAAkBg",
            secretKeyId: "gOwKnM0kiG9n9R6NpCZLOlQNVbNNu4",
            securityToken: ""
        )
        
        let config = OSSClientConfiguration()
        config.maxRetryCount = 3
        config.timeoutIntervalForRequest = 30
        
        client = OSSClient(
            endpoint: "https://oss-cn-shenzhen.aliyuncs.com",
            credentialProvider: credential,
            clientConfiguration: config
        )
    }
    
    func uploadImage(image: UIImage, bucketName: String, objectKey: String) {
        guard let imageData = image.jpegData(compressionQuality: 0.8) else {
            uploadResult = "图片转换失败"
            return
        }
        
        let put = OSSPutObjectRequest()
        put.bucketName = bucketName
        put.objectKey = objectKey
        put.uploadingData = imageData
        put.uploadProgress = { bytesSent, totalBytesSent, totalBytesExpectedToSend in
            DispatchQueue.main.async {
                self.uploadProgress = Double(totalBytesSent) / Double(totalBytesExpectedToSend)
            }
        }
        let task = client?.putObject(put)
        task?.continue({ task in
            DispatchQueue.main.async {
                if let error = task.error {
                    self.uploadResult = "上传失败: \(error.localizedDescription)"
                } else {
                    self.uploadResult = "上传成功! 文件URL: https://\(put.bucketName).oss-cn-shenzhen.aliyuncs.com/\(put.objectKey)"
                }
            }
            return nil
        })
    }
    
    
    
    
    
    func uploadImage(image: UIImage, bucketName: String, objectKey: String,completion: @escaping (String, Error?) -> Void
    ) {
        guard let imageData = image.jpegData(compressionQuality: 0.8) else {
            uploadResult = "图片转换失败"
            return
        }
        
        let put = OSSPutObjectRequest()
        put.bucketName = bucketName
        put.objectKey = objectKey
        put.uploadingData = imageData
        put.uploadProgress = { bytesSent, totalBytesSent, totalBytesExpectedToSend in
            DispatchQueue.main.async {
                self.uploadProgress = Double(totalBytesSent) / Double(totalBytesExpectedToSend)
            }
        }
        let task = client?.putObject(put)
        task?.continue({ task in
            DispatchQueue.main.async {
                if let error = task.error {
                    self.uploadResult = "上传失败: \(error.localizedDescription)"
                    completion("上传失败\((error.localizedDescription))", error)
                } else {
                    self.uploadResult = "https://\(put.bucketName).oss-cn-shenzhen.aliyuncs.com/\(put.objectKey)"
                    completion(self.uploadResult,nil)
                }
            }
            return nil
        })
    }
    
    
    
    
    
    
    
}

